package mc.contents.web.servlet;

import mc.contents.pojo.view.ReshelfItem;
import mc.contents.pojo.view.Shopcard;
import mc.contents.web.common.AbstractResponseHttpServlet;
import mc.contents.web.common.CrawRequest;
import mc.contents.web.common.CrawResult;
import mc.contents.web.request.ReshelfCrawRequest;
import mc.contents.web.result.ReshelfCrawResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by LuoHui on 14-11-26.
 */
@WebServlet(name = "reshelfResponse",urlPatterns="/reshelfResponse",asyncSupported=false)
public class ReshelfResponseServlet extends AbstractResponseHttpServlet {
    private static Logger log = LoggerFactory.getLogger( ReshelfResponseServlet.class );
    private static final String name = "reshelf";

    public ReshelfResponseServlet(  ) {
        super( name );
    }

    @Override
    public CrawResult setResult( HttpServletRequest request, Long request_id, String pageIndex,CrawRequest crawReq ) {
        ReshelfCrawResult crawResult = new ReshelfCrawResult();
        crawResult.setId( request_id );
        crawResult.setPageIndex( Integer.parseInt( pageIndex ) );
        crawResult.setItems( getItems( request ) );
        return crawResult;
    }

    private List<ReshelfItem> getItems( HttpServletRequest request ) {
        List<ReshelfItem> items = new ArrayList<>(  );
        try{
            String num_iid = request.getParameter( "num_iid" );
            String volume = request.getParameter( "volume" );
            String sellerId = request.getParameter( "sellerId" );

            if( StringUtils.isNotEmpty( num_iid )) {
                log.info( "get items : {}",num_iid );
                String[] idArray = num_iid.split( "," );
                String[] volumeArray = volume.split( "," );
                String[] sellerIdArray = sellerId.split( "," );
                for ( int i = 0; i < idArray.length; i++ ) {
                    ReshelfItem item = new ReshelfItem();
                    item.setNum_iid( idArray[i] );
                    item.setVolume( volumeArray[i] == null ? null : volumeArray[i].replace( "???", "" ) );
                    item.setSellerId( sellerIdArray[i] );
                    items.add( item );
                }
            }
        }catch ( Exception e ){
            log.error( "getItems : ",e );
        }
        return items;
    }
}
